<?php
declare (strict_types=1);

namespace app\common\model;

use addons\Sms\facade\Sms;

class UserCode extends Base
{
    /**
     * 获取短信验证码
     */
    public static function sendMsgCode($mobile, $action): array
    {
        try {
            $time = time();
            //60秒内只能获取一次验证码
            $has = parent::where(['mobile' => $mobile, 'action' => $action])
                ->where('create_time', '>=', $time - 60)->find();
            if ($has) {
                throw new \Exception('60秒内只能发送一次');
            }
            $code = rand(100000, 999999);
            $content = '您的验证码是【' . $code . '】，验证码5分钟内有效';
            $res = Sms::send($mobile, $content);
            if ($res['code'] != 200) {
                throw new \Exception($res['msg']);
            }
            $end_time = $time + 300;
            $data = [
                'mobile' => $mobile,
                'code' => $code,
                'action' => $action,
                'end_time' => $end_time,
                'create_time' => $time,
                'update_time' => $time
            ];
            parent::create($data);

        } catch (\Exception $e) {

            return ['code' => -1, 'msg' => $e->getMessage()];
        }

        return ['code' => 1, 'msg' => '已发送'];
    }

    /**
     * 校验短信验证码
     */
    public static function verifyMsgCode($mobile, $code, $action): bool|string
    {
        try {
            $time = time();
            $has = parent::where(['mobile' => $mobile, 'code' => $code, 'action' => $action])
                ->where('end_time', '>=', $time)->find();
            if (!$has) {
                throw new \Exception('验证码无效');
            }
            $has->delete();

        } catch (\Exception $e) {

            return $e->getMessage();
        }

        return true;
    }
}